//
//  CrazyChatViewController.m
//  webSocket
//
//  Created by 马军凯 on 2019/1/14.
//  Copyright © 2019年 ZH. All rights reserved.
//

#import "CrazyChatViewController.h"
#import "CrazyInputBackView.h" //下面的聊天输入框
#import "CrazyChatMineTextCell.h" //自己发送的文本cell
#import "CrazyChatMineImageCell.h" //自己发送的图片cell
#import "CrazyChatMineVoiceCell.h" //自己发送的语音cell
#import "CrazyChatMineGoodsCell.h" //自己发送的商品cell
#import "CrazyChatMineOrderCell.h" //自己发送的订单cell
#import "CrazyChatCustomImageCell.h" //客服发送的图片cell
#import "CrazyChatCustomTextCell.h" //客服发送的文本cell
#import "CrazyChatCustomGoodsCell.h" //客服发送的商品cell
#import "CrazyChatCustomOrderCell.h" //客服发送的订单cell
#import "CrazyChatGoodsLinkCell.h" //宝贝链接
#import "CrazyChatDataModel.h" //数据model
#import "CrazyChatExpressionModel.h" //表情model
#import "CrazyChatExpressionText.h" //表情文本
#import "CrazyChatSettingViewController.h" //设置
#import <AVFoundation/AVFoundation.h> //音频的播放
#import "CrazyChatGoodsListView.h" //商品列表
#import "CrazyChatOrderListView.h" //订单列表

@interface CrazyChatViewController ()
<UITextViewDelegate,
UITableViewDataSource,
UITableViewDelegate,
CrazyChatChooseExpressionDelegate, //选择表情
CrazyChatAddExtensionDelegate, //选择+号扩展
UIImagePickerControllerDelegate,
UINavigationControllerDelegate>
{
    BOOL isClickVoice; //是不是点击了语音
    BOOL isClickAddExtension; //是不是点击了扩展
    BOOL isClickExpression; //是不是点击了表情
    CGFloat textHeight; //输入内容高度（可以变化的）
    BOOL isShowKeyBoard; //是否展示了键盘
    CGFloat keyBoardHeight; //键盘的高度
    CGFloat expressionHeight; //表情的高度
    BOOL isClickExtensionCloseKeyBoard; //是不是点击扩展取消的键盘
    BOOL isClickExpressionCloseKeyBoard; //是不是点击表情取消的键盘
    NSIndexPath *selectIndexPath; //上一个播放的语音
    BOOL isClickPlayVoice; //是否点击播放语音
    NSString *lastDataID; //查询历史记录的最后一个ID
}

@property (nonatomic, strong) CrazyInputBackView *inputBackView; //输入框
@property (nonatomic, retain) NSMutableArray *CrazyChatDataArray; //数据源
@property (nonatomic, retain) NSMutableArray *expressionArray; //表情数组
@property (nonatomic, strong) AVPlayer *player; //播放
@property (nonatomic, assign) BOOL isRefresh; //是否刷新数据
@property (nonatomic, strong) UIActivityIndicatorView *activityView; //刷新的时候转圈
@property (nonatomic, strong) CrazyChatGoodsListView *goodsListView; //商品列表
@property (nonatomic, strong) CrazyChatOrderListView *orderListView; //订单列表

@end

@implementation CrazyChatViewController

#pragma mark 页面将显示
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //禁止使用第三方IQKeyBoard
    [[IQKeyboardManager sharedManager] setEnable:NO];
    //清除未读消息
    NSInteger noReadCount = [[NSUserDefaults standardUserDefaults] integerForKey:self.store_id];
    NSInteger allNoReadCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"CrazyChatAllNoReadMessageCount"];
    [[NSUserDefaults standardUserDefaults] setInteger:(allNoReadCount - noReadCount) forKey:@"CrazyChatAllNoReadMessageCount"];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:self.store_id];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark 页面要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //展开使用第三方
    [[IQKeyboardManager sharedManager] setEnable:YES];
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
}

#pragma mark 销毁页面dealloc
- (void)dealloc {
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"销毁");
}

#pragma mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CRAZY_RGBR(242);
    if ([self.store_id isEqualToString:@""] || self.store_id == nil) {
        CrazyWeakSelf;
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"连接失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
        //确定
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        [alertVC addAction:sureAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    //赋值
    [self getValues];
    //UI
    [self setUI];
    //创建tableView
    [self createTableView];
    //刷新
    [self createRefresh];
    //通知
    [self createNoticeFunction];
    //网络请求
    dispatch_async(dispatch_get_main_queue(), ^{
        [self getHistoryMessageData];
    });
    [self getStoreMessageData];
    //解析表情文件
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDataExpression];
    });
    //预聊天消息
    NSDictionary *params = @{@"TYPE" : @"MATCH_CUSTOMER", @"DATA" : @{@"TARGET_ID" : self.store_id, @"DIVERSION_ID" : self.diversionID}};
    [[CrazySocketUtility sharedSocketManager] sendDataToServer:params];
}
#pragma mark 赋值
- (void)getValues {
    isClickVoice = NO; //语音
    isClickAddExtension = NO; //+号扩展
    isClickExpression = NO; //表情
    textHeight = 0; //文本高度
    isClickPlayVoice = NO;
    lastDataID = @"0";
    self.hideHeight = CRAZY_NAVIGATION_HEIGHT;
    selectIndexPath = [NSIndexPath indexPathForRow:-1 inSection:-1];
    isClickExtensionCloseKeyBoard = NO; //点击+号扩展关闭键盘
    isClickExpressionCloseKeyBoard = NO; //点击表情关闭键盘
}
#pragma mark 通知
- (void)createNoticeFunction {
    //键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardWillHideNotification object:nil];
    //后台接收到消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CrazyChatDelivierdMessage:) name:@"CrazyChatDeliverdMessageData" object:nil];
    //后台给返回的数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CrazyChatBackMessage:) name:@"CrazyChatBackMessageData" object:nil];
    //发送语音
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CrazyChatSendVoiceData:) name:@"CrazyChatSendVoice" object:nil];
    //关闭语音
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeNowPlayVoice) name:@"CrazyChatClosePlayVoice" object:nil];
    //播放语音结束
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeNowPlayVoice) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
#pragma mark 键盘弹出隐藏
//键盘弹出
- (void)keyBoardWillChangeFrame:(NSNotification *)sender {
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    if (isClickAddExtension) {
        [self changeAddExtensionStatus];
    }
    if (isClickExpression) {
        [self changeExpressionStatus];
    }
    isClickExtensionCloseKeyBoard = NO;
    isClickExpressionCloseKeyBoard = NO;
    
    CGRect keyboardFrame = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    isShowKeyBoard = YES;
    keyBoardHeight = keyboardFrame.size.height;
    expressionHeight = 0;
    _inputBackView.y = CRAZY_SCREEN_HEIGHT - self.hideHeight - keyboardFrame.size.height - _inputBackView.downAllBackView.height;
    _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
    //移动到数据的最后一条
    [self removeTableViewToLastData];
}
//键盘隐藏
- (void)keyBoardDidHide:(NSNotification *)sender {
    isShowKeyBoard = NO;
    keyBoardHeight = 0;
    _inputBackView.y = CRAZY_SCREEN_HEIGHT - self.hideHeight - _inputBackView.downAllBackView.height - CRAZY_HOME_HEIGHT;
    _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
    if (isClickExtensionCloseKeyBoard) {
        [self changeAddExtensionStatus];
        expressionHeight = 0;
    }
    if (isClickExpressionCloseKeyBoard) {
        expressionHeight = 240;
        [self changeExpressionStatus];
    }
}

#pragma mark 导航栏设置
- (void)clickNavigationRightSettingItem:(UIButton *)btn {
    [self clickNavigationRightGoSettingItem];
}
- (void)clickNavigationRightGoSettingItem {
    NSLog(@"走父视图的方法");
    CrazyChatSettingViewController *vc = [[CrazyChatSettingViewController alloc] init];
    vc.shopID = self.store_id;
    vc.shopName = self.shopName;
    vc.shopHeadURL = self.shopHeadURL;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 进店
- (void)clickNavigationRightGoItem {
    [self clickNavigationRightGoShopItem];
}
- (void)clickNavigationRightGoShopItem {
}

#pragma mark 创建UITableView
- (void)createTableView {//CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, CRAZY_SCREEN_HEIGHT - self.hideHeight - CRAZY_HOME_HEIGHT - 50)
    _chatTableView = [[CrazyChatTableView alloc] initWithFrame:CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, CRAZY_SCREEN_HEIGHT - self.hideHeight - CRAZY_HOME_HEIGHT - 50) style:UITableViewStylePlain];
    _chatTableView.dataSource = self;
    _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _chatTableView.delegate = self;
    _chatTableView.estimatedRowHeight = 0;
    _chatTableView.estimatedSectionHeaderHeight = 0;
    _chatTableView.estimatedSectionFooterHeight = 0;
    _chatTableView.backgroundColor = CRAZY_RGBR(229);
    //宝贝链接
    [_chatTableView registerClass:[CrazyChatGoodsLinkCell class] forCellReuseIdentifier:@"CrazyChatGoodsLinkCell"];
    //自己发送的文本
    [_chatTableView registerClass:[CrazyChatMineTextCell class] forCellReuseIdentifier:CrazyChatMineTextIdentifier];
    //自己发送的图片
    [_chatTableView registerClass:[CrazyChatMineImageCell class] forCellReuseIdentifier:CrazyChatMineImageIdentifier];
    //自己发送的语音
    [_chatTableView registerClass:[CrazyChatMineVoiceCell class] forCellReuseIdentifier:CrazyChatMineVoiceIdentifier];
    //自己发送的商品
    [_chatTableView registerClass:[CrazyChatMineGoodsCell class] forCellReuseIdentifier:CrazyChatMineGoodsIdentifier];
    //自己发送的订单
    [_chatTableView registerClass:[CrazyChatMineOrderCell class] forCellReuseIdentifier:CrazyChatMineOrderIdentifier];
    //客服发送的图片
    [_chatTableView registerClass:[CrazyChatCustomImageCell class] forCellReuseIdentifier:CrazyChatCustomImageIdentifier];
    //客服发送的文本
    [_chatTableView registerClass:[CrazyChatCustomTextCell class] forCellReuseIdentifier:CrazyChatCustomTextIdentifier];
    //客服发送的商品
    [_chatTableView registerClass:[CrazyChatCustomGoodsCell class] forCellReuseIdentifier:CrazyChatCustomGoodsIdentifier];
    [self.view addSubview:_chatTableView];
    _chatTableView.tableFooterView = [UIView new];
}

#pragma mark UITableView dataSource
//几组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
//每组个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.CrazyChatDataArray.count;
}
#pragma mark UITableView delegate
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CrazyChatDataModel *model = [self.CrazyChatDataArray objectAtIndex:indexPath.row];
    
    if ([model.MESSAGE_TYPE isEqualToString:@"TEXT"]) {
        //文本
        if ([model.FORM_TYPE isEqualToString:@"CUSTOMER"]) {
            CrazyChatCustomTextCell *cell = [CrazyChatCustomTextCell cellWithTableView:_chatTableView];
            //赋值
            [UIView performWithoutAnimation:^{
                [cell setCellValueWithHeadURL:self.shopHeadURL content:[self textChangeWithText:model.MESSAGE_DATA]];
            }];
            
            
            return cell;
        } else if ([model.FORM_TYPE isEqualToString:@"USER"]) {
            CrazyChatMineTextCell *cell = [CrazyChatMineTextCell cellWithTableView:_chatTableView];
            //赋值
            [UIView performWithoutAnimation:^{
                [cell setCellValueWithHeadURL:AVATAR content:[self textChangeWithText:model.MESSAGE_DATA] repeatType:model.repeatType];
            }];
            
            //重发按钮
            [cell.mineTextRepeatBtn addTarget:self action:@selector(clickTextRepeatMessageData:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
        
    } else if ([model.MESSAGE_TYPE isEqualToString:@"IMAGE"]) {
        //图片
        if ([model.FORM_TYPE isEqualToString:@"CUSTOMER"]) {
            CrazyChatCustomImageCell *cell = [CrazyChatCustomImageCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:self.shopHeadURL picURL:model.MESSAGE_DATA];
            
            return cell;
        } else if ([model.FORM_TYPE isEqualToString:@"USER"]) {
            CrazyChatMineImageCell *cell = [CrazyChatMineImageCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:AVATAR picURL:model.MESSAGE_DATA repeatType:model.repeatType];
            //重发按钮
            [cell.mineImageRepeatBtn addTarget:self action:@selector(clickImageRepeatMessageData:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
    } else if ([model.MESSAGE_TYPE isEqualToString:@"VOICE"]) {
        //语音
        if ([model.FORM_TYPE isEqualToString:@"CUSTOMER"]) {
            
        } else if ([model.FORM_TYPE isEqualToString:@"USER"]) {
            CrazyChatMineVoiceCell *cell = [CrazyChatMineVoiceCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:AVATAR timeString:model.VOICE_TIME repeatType:model.repeatType isPlay:model.isPlayVoice];
            //重发按钮
            [cell.mineVoiceRepeatBtn addTarget:self action:@selector(clickVoiceRepeatMessageData:) forControlEvents:UIControlEventTouchUpInside];
            //语音播放
            [cell.mineVoicePlayBtn addTarget:self action:@selector(clickPlayVoiceBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
    } else if ([model.MESSAGE_TYPE isEqualToString:@"GOODS"]) {
        //商品
        if ([model.FORM_TYPE isEqualToString:@"CUSTOMER"]) {
            CrazyChatCustomGoodsCell *cell = [CrazyChatCustomGoodsCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:self.shopHeadURL picURL:model.GOODSURL title:model.GOODSTITLE price:model.GOODSPRICE];
            //商品查看详情
            [cell.customGoodsCheckBtn addTarget:self action:@selector(clickCheckCustomSendGoodsBtn:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        } else if ([model.FORM_TYPE isEqualToString:@"USER"]) {
            CrazyChatMineGoodsCell *cell = [CrazyChatMineGoodsCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:AVATAR picURL:model.GOODSURL title:model.GOODSTITLE price:model.GOODSPRICE repeatType:model.repeatType];
            //重发按钮
            [cell.mineGoodsRepeatBtn addTarget:self action:@selector(clickGoodsRepeatMessageData:) forControlEvents:UIControlEventTouchUpInside];
            //查看商品详情
            [cell.mineGoodsCheckBtn addTarget:self action:@selector(clickCheckMineSendGoodsBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
    } else if ([model.MESSAGE_TYPE isEqualToString:@"ORDER"]) {
        //订单
        if ([model.FORM_TYPE isEqualToString:@"CUSTOMER"]) {
            CrazyChatCustomOrderCell *cell = [CrazyChatCustomOrderCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:AVATAR picURL:model.GOODSURL title:model.GOODSTITLE attr:model.GOODSATTR price:model.GOODSPRICE count:model.GOODSNUM status:model.ORDER_STATUS];
            //查看订单按钮
            [cell.customOrderCheckBtn addTarget:self action:@selector(clickCheckCustomSendOrderBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        } else if ([model.FORM_TYPE isEqualToString:@"USER"]) {
            CrazyChatMineOrderCell *cell = [CrazyChatMineOrderCell cellWithTableView:_chatTableView];
            //赋值
            [cell setCellValueWithHeadURL:AVATAR picURL:model.GOODSURL title:model.GOODSTITLE attr:model.GOODSATTR price:model.GOODSPRICE count:model.GOODSNUM status:model.ORDER_STATUS repeatType:model.repeatType];
            //查看订单按钮
            [cell.mineOrderCheckBtn addTarget:self action:@selector(clickCheckMineSendOrderBtn:) forControlEvents:UIControlEventTouchUpInside];
            //重发按钮
            [cell.mineOrderRepeatBtn addTarget:self action:@selector(clickOrderRepeatMessageData:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
        }
    } else if ([model.MESSAGE_TYPE isEqualToString:@"GOODS_LINK"]) {
        //宝贝链接
        CrazyChatGoodsLinkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrazyChatGoodsLinkCell"];
        if (cell == nil) {
            cell = [[CrazyChatGoodsLinkCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CrazyChatGoodsLinkCell"];
        }
        //发送宝贝链接
        [cell.sendBtn addTarget:self action:@selector(clickSendGoodsLinkeBtn:) forControlEvents:UIControlEventTouchUpInside];
        //商品图片
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.GOODSURL] placeholderImage:CRAZY_DEFAULT_LOADIMAGE];
        //标题
        cell.titleLabel.text = model.GOODSTITLE;
        //价格
        cell.priceLabel.text = [NSString stringWithFormat:@"%@%@", @"¥", model.GOODSPRICE];
        return cell;
    }
    
    UITableViewCell *otherCell = [[UITableViewCell alloc] init];
    return otherCell;
}
//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    
    if ([model.MESSAGE_TYPE isEqualToString:@"TEXT"]) {
        NSMutableAttributedString *str = [self textChangeWithText:model.MESSAGE_DATA];
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:14];
        label.numberOfLines = 0;
        label.attributedText = str;
        CGSize maxSize = CGSizeMake(CRAZY_SCREEN_WIDTH - 120 - 20, 9999);
        CGSize size = [label sizeThatFits:maxSize];
        CGFloat height = 0;
        if (size.height < 40) {
            height = 40;
        } else {
            height = size.height + 20;
        }
        return height + 20;
    } else if ([model.MESSAGE_TYPE isEqualToString:@"IMAGE"]) {
        //图片
        return 120;
    } else if ([model.MESSAGE_TYPE isEqualToString:@"VOICE"]) {
        //语音
        return 60;
    } else if ([model.MESSAGE_TYPE isEqualToString:@"GOODS"]) {
        //商品
        return 120;
    } else if ([model.MESSAGE_TYPE isEqualToString:@"ORDER"]) {
        //订单
        return 120;
    } else if ([model.MESSAGE_TYPE isEqualToString:@"GOODS_LINK"]) {
        //宝贝连接
        return 120;
    } else {
        return 0;
    }
}
#pragma mark UITableView didselect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark 发送宝贝链接
- (void)clickSendGoodsLinkeBtn:(UIButton *)sender {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    [self sendGoodsLinkWithGoodsID:self.goods_id];
}
//发送宝贝
- (void)sendGoodsLinkWithGoodsID:(NSString *)goodsID {
    //当前时间
    NSString *timeString = [Crazy_TimeChange currentTimeChangeTimeString];
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    NSDictionary *dict = @{@"MESSAGE_DATA" : goodsID, @"MESSAGE_TYPE" : @"GOODS", @"FORM_TYPE" : @"USER", @"MESSAGE_ID" : timeString};
    [model setCustomSendMessage:dict tableView:_chatTableView];
    model.repeatType = @"1";
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
    //发送给后台
    [self CrazyChatSendMessageWithMessageID:timeString messageData:goodsID messageType:@"GOODS"];
}

#pragma mark UI 下面的输入框
- (void)setUI {
    if (_inputBackView == nil) {
        _inputBackView = [CrazyInputBackView sharedDefault];
        _inputBackView.frame = CGRectMake(0, CRAZY_SCREEN_HEIGHT - self.hideHeight - 50 - CRAZY_HOME_HEIGHT, CRAZY_SCREEN_WIDTH, 50 + CRAZY_HOME_HEIGHT);
        _inputBackView.backgroundColor = CRAZY_RGBR(242);
    }
    _inputBackView.inputTextView.delegate = self;
    _inputBackView.expressionView.delegate = self;
    _inputBackView.extensionBackView.delegate = self;
    //切换文本 语音
    [_inputBackView.changeVoiceAndTextBtn addTarget:self action:@selector(clickChangeVoiceAndTextBtn:) forControlEvents:UIControlEventTouchUpInside];
    //笑脸
    [_inputBackView.smilingFacebtn addTarget:self action:@selector(clickSmilingFaceBtn) forControlEvents:UIControlEventTouchUpInside];
    //展开+号的扩展
    [_inputBackView.addExtensionBtn addTarget:self action:@selector(clickAddExtensionBtn) forControlEvents:UIControlEventTouchUpInside];
    //点击发送按钮
    [_inputBackView.sendBtn addTarget:self action:@selector(clickSendBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_inputBackView];
    [_inputBackView bringSubviewToFront:self.view];
}

#pragma mark 切换语音和文本
- (void)clickChangeVoiceAndTextBtn:(UIButton *)sender {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    [_inputBackView.inputTextView resignFirstResponder];
    //如果+号扩展展开了 就要关闭
    if (isClickAddExtension) {
        [self changeAddExtensionStatus];
    }
    //如果表情展开了  要关闭
    if (isClickExpression) {
        [self changeExpressionStatus];
    }
    //改变语音和文本的状态
    [self changeVoiceAndTextStatus];
}
//改变语音和文本的状态
- (void)changeVoiceAndTextStatus {
    isClickVoice = !isClickVoice;
    _inputBackView.changeVoiceAndTextBtn.selected = isClickVoice;
    _inputBackView.smilingFacebtn.hidden = isClickVoice;
    _inputBackView.inputTextView.hidden = isClickVoice;
    _inputBackView.voiceBtn.hidden = !isClickVoice;
    if (isClickVoice) { //语音状态
        _inputBackView.inputTextView.height = _inputBackView.inputTextView.height - textHeight;
    } else { //文本状态
        _inputBackView.inputTextView.height = _inputBackView.inputTextView.height + textHeight;
    }
    [self setLayoutHeight];
}

#pragma mark 点击笑脸
- (void)clickSmilingFaceBtn { //点击笑脸的时候，要把+号扩展的内容取消，让表情显示或者隐藏
    //判断+号扩展是否展开 展开了 就隐藏 展示笑脸
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    if (isClickAddExtension) {
        isClickAddExtension = NO;
        _inputBackView.extensionBackView.hidden = !isClickAddExtension;
        _inputBackView.extensionBackView.y = 0;
        isClickExpression = YES;
        expressionHeight = 240;
        _inputBackView.expressionView.hidden = !isClickExpression;
        _inputBackView.expressionView.y = _inputBackView.downAllBackView.height;
    } else {
        //+号没有展开  然后判断键盘在没在，在-隐藏键盘展示笑脸，不在-就直接展示笑脸
        if (!_inputBackView.inputTextView.isFirstResponder) {
            [self changeExpressionStatus];
        } else {
            isClickExpressionCloseKeyBoard = YES;
            isClickExtensionCloseKeyBoard = NO;
            [_inputBackView.inputTextView resignFirstResponder];
        }
    }
}

#pragma mark 改变表情扩展的状态
- (void)changeExpressionStatus {
    isClickExpression = !isClickExpression;
    _inputBackView.expressionView.hidden = !isClickExpression;
    CGFloat height = isClickExpression ? -240 : 240;
    expressionHeight = isClickExpression ? 240 : 0;
    _inputBackView.y = _inputBackView.y + height;
    _inputBackView.height = _inputBackView.height - height;
    _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
    _inputBackView.expressionView.y = _inputBackView.downAllBackView.height;
    //移动到数据的最后一条
    [self removeTableViewToLastData];
}

#pragma mark 点击加号那个扩展
- (void)clickAddExtensionBtn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    if (isClickVoice) {
        //改变语音和文本的状态
        [self changeVoiceAndTextStatus];
    }
    if (isClickExpression) {
        isClickAddExtension = YES;
        _inputBackView.extensionBackView.hidden = !isClickAddExtension;
        _inputBackView.extensionBackView.y = _inputBackView.downAllBackView.height;
        isClickExpression = NO;
        expressionHeight = 0;
        _inputBackView.expressionView.hidden = !isClickExpression;
    } else {
        if (!_inputBackView.inputTextView.isFirstResponder) {
            [self changeAddExtensionStatus];
        } else {
            isClickExtensionCloseKeyBoard = YES;
            isClickExpressionCloseKeyBoard = NO;
            [_inputBackView.inputTextView resignFirstResponder];
        }
    }
}

#pragma mark 改变扩展的状态
- (void)changeAddExtensionStatus {
    isClickAddExtension = !isClickAddExtension;
    _inputBackView.extensionBackView.hidden = !isClickAddExtension;
    CGFloat height = isClickAddExtension ? -240.00f : 240.00f;
    _inputBackView.y = _inputBackView.y + height;
    _inputBackView.height = _inputBackView.height - height;
    _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
    _inputBackView.extensionBackView.y = _inputBackView.downAllBackView.height;
    //移动到数据的最后一条
    [self removeTableViewToLastData];
}

#pragma mark 高度的设置
- (void)changeTextViewHeight {
    _inputBackView.inputTextView.font = [UIFont systemFontOfSize:15];
    CGSize maxSize = CGSizeMake(_inputBackView.inputTextView.frame.size.width, 106);
    CGSize size = [_inputBackView.inputTextView sizeThatFits:maxSize];
    if (size.height < 40) {
        textHeight = 0;
        _inputBackView.inputTextView.height = 34;
    } else {
        if (size.height >= 105.66667) { //17  104
            textHeight = 94 - 34;
            _inputBackView.inputTextView.height = 94;
            [_inputBackView.inputTextView setContentOffset:CGPointMake(0, _inputBackView.inputTextView.contentSize.height - 94) animated:NO];
        } else {
            textHeight = size.height - 34 - 11;
            _inputBackView.inputTextView.height = size.height - 11;
            [_inputBackView.inputTextView setContentOffset:CGPointMake(0, _inputBackView.inputTextView.contentSize.height - _inputBackView.inputTextView.height) animated:NO];
        }
    }
    [self setLayoutHeight];
}
//布局
- (void)setLayoutHeight {
    _inputBackView.allWhiteBackView.height = _inputBackView.inputTextView.height + 6;
    _inputBackView.downAllBackView.height = _inputBackView.allWhiteBackView.height + 10;
    if (isClickExpression) {
        _inputBackView.height = _inputBackView.downAllBackView.height + expressionHeight + CRAZY_HOME_HEIGHT;
        _inputBackView.y = CRAZY_SCREEN_HEIGHT - _inputBackView.height - self.hideHeight;
        _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
        _inputBackView.expressionView.y = _inputBackView.downAllBackView.height;
    } else {
        if (isShowKeyBoard) {
            _inputBackView.height = _inputBackView.downAllBackView.height;
            _inputBackView.y = CRAZY_SCREEN_HEIGHT - _inputBackView.height - self.hideHeight - keyBoardHeight;
            _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
        } else {
            _inputBackView.height = _inputBackView.downAllBackView.height + CRAZY_HOME_HEIGHT + expressionHeight;
            _inputBackView.y = CRAZY_SCREEN_HEIGHT - _inputBackView.height - self.hideHeight;
            _chatTableView.height = _inputBackView.y - CRAZY_NAVIGATION_HEIGHT + self.hideHeight;
        }
    }
}

#pragma mark 表情的代理返回方法
//往UITextView中插入表情
- (void)CrazyChatSelectExpression:(CrazyChatExpressionModel *)model {
    CrazyChatExpressionText *emoji = [[CrazyChatExpressionText alloc] init];
    emoji.image = [UIImage imageNamed:model.image];
    emoji.Tag = model.name;
    emoji.bounds = CGRectMake(0, -6, 22, 22);
    NSAttributedString *emojiStr = [NSAttributedString attributedStringWithAttachment:emoji];
    [_inputBackView.inputTextView.textStorage insertAttributedString:emojiStr atIndex:_inputBackView.inputTextView.selectedRange.location];
    _inputBackView.inputTextView.selectedRange = NSMakeRange(_inputBackView.inputTextView.selectedRange.location + 1, 0);
    _inputBackView.sendBtn.hidden = NO;
    _inputBackView.addExtensionBtn.hidden = YES;
    [self changeTextViewHeight];
}
//删除表情
- (void)CrazyChatDeleteExpression {
    if (_inputBackView.inputTextView.text.length > 0) {
        NSMutableAttributedString *oldString = [[NSMutableAttributedString alloc] initWithAttributedString:_inputBackView.inputTextView.attributedText];
        NSRange oldRange = _inputBackView.inputTextView.selectedRange;
        [oldString deleteCharactersInRange:NSMakeRange(oldRange.location - 1, 1)];
        [_inputBackView.inputTextView setAttributedText:oldString];
        if (_inputBackView.inputTextView.text.length == 0) {
            _inputBackView.sendBtn.hidden = YES;
            _inputBackView.addExtensionBtn.hidden = NO;
        }
        [self changeTextViewHeight];
    }
}

#pragma mark CrazyChatAddExtensionDelegate +号内内容点击
- (void)selectAddExtension:(CrazyChatAddExtensionModel *)model {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    if ([model.title isEqualToString:@"相册"]) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *picturePick = [[UIImagePickerController alloc] init];
            picturePick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picturePick.delegate = self;
            picturePick.navigationBar.translucent = NO;
            picturePick.allowsEditing = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:picturePick animated:YES completion:nil];
            });
        } else {
            NSLog(@"读取相册错误");
        }
    } else if ([model.title isEqualToString:@"拍照"]) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *cameraPicker = [[UIImagePickerController alloc] init];
            cameraPicker.delegate = self;
            cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            cameraPicker.allowsEditing = YES;
            cameraPicker.navigationBar.translucent = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:cameraPicker animated:YES completion:nil];
            });
        } else {
            NSLog(@"找不到相机");
        }
    } else if ([model.title isEqualToString:@"订单"]) {
        self.orderListView = [CrazyChatOrderListView sharedDefault];
        self.orderListView.store_id = self.store_id;
        CrazyWeakSelf;
        self.orderListView.block = ^(NSString * _Nonnull orderID, NSString * _Nonnull goods_id) {
            [weakSelf sendGoodsOrderWithGoodsID:goods_id orderNum:orderID];
        };
        [self.orderListView showOrderListView];
    } else if ([model.title isEqualToString:@"商品"]) {
        self.goodsListView = [CrazyChatGoodsListView sharedDefault];
        CrazyWeakSelf;
        self.goodsListView.block = ^(CrazyChatGoodsListDataModel * _Nonnull model) {
            [weakSelf sendGoodsLinkWithGoodsID:model.goods_id];
        };
        [self.goodsListView showGoodsListView];
    } else {
        [self CrazyChatSelectWith:model];
    }
}
//发送订单
- (void)sendGoodsOrderWithGoodsID:(NSString *)goodsID orderNum:(NSString *)orderNum {
    //当前时间
    NSString *timeString = [Crazy_TimeChange currentTimeChangeTimeString];
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    NSDictionary *dict = @{@"MESSAGE_DATA" : orderNum, @"MESSAGE_TYPE" : @"ORDER", @"FORM_TYPE" : @"USER", @"MESSAGE_ID" : timeString, @"GOODS_ID" : goodsID};
    [model setCustomSendMessage:dict tableView:_chatTableView];
    model.repeatType = @"1";
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
    //发送给后台
    NSDictionary *params = @{@"TYPE" : @"MESSAGE",
                             @"DATA" : @{@"MESSAGE_ID" : timeString,
                                         @"MESSAGE_TYPE" : @"ORDER",
                                         @"MESSAGE_DATA" : @{@"ORDER_ID" : orderNum, @"GOODS_ID" : goodsID},
                                         @"TARGET_TYPE" : @"CUSTOMER",
                                         @"TARGET_ID" : self.store_id,
                                         @"DIVERSION_ID" : self.diversionID
                                         }
                             };
    //发送数据
    [[CrazySocketUtility sharedSocketManager] sendDataToServer:params];
}

#pragma mark UIImagePicker
// 取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
// 点击后返回来的图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *personalImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSString *urlString = [CRAZY_CHAT_API_DOMIN stringByAppendingString:@"customer/uploadFile"];
    NSDictionary *params = @{@"file" : personalImage};
    CrazyWeakSelf;
    [CrazyNetWork CrazyHttpFileUpload:urlString HUD:YES parameters:params imageArr:@[personalImage] scale:0.5 nameArr:@[@"file"] fileNameArr:@[@"03030.png"] mimeType:@"image/jpge" block:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([dic[@"error"] intValue] == 0) {
            [weakSelf receiveDataImageDataWith:dic];
        }
    } fail:^(NSError *error, NSString *url) {
        
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//保存图片
- (void)receiveDataImageDataWith:(NSDictionary *)dict {
    NSString *urlString = dict[@"ossUrl"];
    NSString *timeString = [Crazy_TimeChange currentTimeChangeTimeString];
    
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    model.MESSAGE_DATA = urlString;
    model.MESSAGE_TYPE = @"IMAGE";
    model.FORM_TYPE = @"USER";
    model.repeatType = @"1";
    model.MESSAGE_ID = timeString;
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
    //发送数据
    [self CrazyChatSendMessageWithMessageID:timeString messageData:urlString messageType:@"IMAGE"];
}
#pragma mark 点击发送
- (void)clickSendBtn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    NSString *timeString = [Crazy_TimeChange currentTimeChangeTimeString];
    NSString *messageString = [_inputBackView.inputTextView.textStorage getPlainString];
    
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    model.MESSAGE_DATA = messageString;
    model.FORM_TYPE = @"USER";
    model.MESSAGE_ID = timeString;
    model.MESSAGE_TYPE = @"TEXT";
    model.repeatType = @"1";
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
    
    _inputBackView.inputTextView.text = @"";
    [self changeTextViewHeight];
    _inputBackView.sendBtn.hidden = YES;
    _inputBackView.addExtensionBtn.hidden = NO;
    //发送数据
    [self CrazyChatSendMessageWithMessageID:timeString messageData:messageString messageType:@"TEXT"];
}

#pragma mark 移动UITableView到最后一条
- (void)removeTableViewToLastData {
    //移动到最后一条数据
    if (self.CrazyChatDataArray.count) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.CrazyChatDataArray.count-1 inSection:0];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark 给加号里面添加内容
- (void)addExtensionContentWithArray:(NSArray<CrazyChatAddExtensionModel *> *)array {
    [_inputBackView addExtensionContentWithArray:array];
}

#pragma mark +号内扩展内容的点击返回
- (void)CrazyChatSelectWith:(CrazyChatAddExtensionModel *)model {
    
}

#pragma mark 是否有语音按钮，语音按钮的显示或者隐藏
- (void)setIsHaveVoice:(BOOL)isHaveVoice {
    _isHaveVoice = isHaveVoice;
    _inputBackView.changeVoiceAndTextBtn.hidden = !isHaveVoice;
    _inputBackView.allWhiteBackView.x = isHaveVoice ? 45 : 10;
    _inputBackView.allWhiteBackView.width = CRAZY_SCREEN_WIDTH - 45 - _inputBackView.allWhiteBackView.x;
    _inputBackView.smilingFacebtn.x = _inputBackView.allWhiteBackView.width - 35;
    _inputBackView.inputTextView.width = _inputBackView.allWhiteBackView.width - 55;
}

#pragma mark 解析plist表情文件
- (void)getDataExpression {
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"CrazyChatExpression" ofType:@"plist"];
    NSArray *plistArr = [NSArray arrayWithContentsOfFile:plistPath];
    for (NSDictionary *dict in plistArr) {
        CrazyChatExpressionModel *model = [[CrazyChatExpressionModel alloc] init];
        model.image = dict[@"image"];
        model.name = dict[@"name"];
        model.ID = dict[@"id"];
        [self.expressionArray addObject:model];
    }
    _inputBackView.expressionView.dataArray = self.expressionArray;
    [_chatTableView reloadData];
}

#pragma mark 输入框的代理方法 UITextView delegate
- (void)textViewDidChange:(UITextView *)textView {
    textView.font = [UIFont systemFontOfSize:15];
    [self changeTextViewHeight];
    //+号扩展改发送
    if (textView.text.length == 0) {
        _inputBackView.sendBtn.hidden = YES;
        _inputBackView.addExtensionBtn.hidden = NO;
    } else {
        _inputBackView.sendBtn.hidden = NO;
        _inputBackView.addExtensionBtn.hidden = YES;
    }
}
//return 按钮
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        NSLog(@"发送");
        [self clickSendBtn];
        return NO;
    }
    return YES;
}
#pragma mark 滑动tableView关闭键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == _chatTableView) {
        if (isShowKeyBoard) {
            [_inputBackView.inputTextView resignFirstResponder];
        } else if (isClickExpression) {
            [self changeExpressionStatus];
        } else if (isClickAddExtension) {
            [self changeAddExtensionStatus];
        }
    }
}

#pragma mark 是否有宝贝链接
- (void)setIsHaveGoodsLink:(BOOL)isHaveGoodsLink {
    _isHaveGoodsLink = isHaveGoodsLink;
    //数据
    if (isHaveGoodsLink) {
        NSString *urlString = [CRAZY_CHAT_API_DOMIN stringByAppendingString:@"customer/getGoodsInfo"];
        NSDictionary *params = @{@"goods_id" : self.goods_id};
        CrazyWeakSelf;
        [CrazyNetWork CrazyRequest_Post:urlString HUD:NO parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
            if ([[NSString stringWithFormat:@"%@",dic[@"code"]] isEqualToString:@"0"]) {
                NSDictionary *dataDict = dic[@"data"];
                CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
                model.GOODSTITLE = [NSString stringWithFormat:@"%@", dataDict[@"goods_name"]];
                model.GOODSPRICE = [NSString stringWithFormat:@"%@", dataDict[@"price"]];
                model.MESSAGE_TYPE = @"GOODS_LINK";
                model.GOODSURL = [NSString stringWithFormat:@"%@", dataDict[@"file"]];
                [weakSelf.CrazyChatDataArray addObject:model];
                [_chatTableView reloadData];
            } else {
                [JKToast showWithText:dic[@"data"]];
            }
        } fail:^(NSError *error, NSString *url) {
            
        }];
    }
}

#pragma mark 后台接收到消息了
- (void)CrazyChatDelivierdMessage:(NSNotification *)sender {
    NSDictionary *infoDict = sender.userInfo;
    for (CrazyChatDataModel *model in self.CrazyChatDataArray) {
        if ([model.MESSAGE_ID isEqualToString:infoDict[@"MESSAGE_ID"]]) {
            model.repeatType = @"0";
        }
    }
    [_chatTableView reloadData];
}

#pragma mark 后台发送回来的数据
- (void)CrazyChatBackMessage:(NSNotification *)sender {
    NSDictionary *userInfo = sender.userInfo;
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    [model setCustomSendMessage:userInfo tableView:_chatTableView];
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
}

#pragma mark 重发按钮
//图片
- (void)clickImageRepeatMessageData:(UIButton *)btn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    CrazyChatMineImageCell *cell = (CrazyChatMineImageCell *)btn.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    [self repeatMessageDataWithIndex:indexPath.row];
}
//语音
- (void)clickVoiceRepeatMessageData:(UIButton *)btn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    CrazyChatMineVoiceCell *cell = (CrazyChatMineVoiceCell *)btn.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    NSDictionary *params = @{@"TYPE" : @"MESSAGE",
                             @"DATA" : @{@"MESSAGE_ID" : model.MESSAGE_ID,
                                         @"MESSAGE_TYPE" : @"VOICE",
                                         @"MESSAGE_DATA" : model.MESSAGE_DATA,
                                         @"VOICE_TIME" : model.VOICE_TIME,
                                         @"TARGET_TYPE" : @"CUSTOMER",
                                         @"TARGET_ID" : self.store_id,
                                         @"DIVERSION_ID" : self.diversionID
                                         }
                             };
    //发送数据
    [[CrazySocketUtility sharedSocketManager] sendDataToServer:params];
}
//文本
- (void)clickTextRepeatMessageData:(UIButton *)btn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    CrazyChatMineTextCell *cell = (CrazyChatMineTextCell *)btn.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    [self repeatMessageDataWithIndex:indexPath.row];
}
//商品
- (void)clickGoodsRepeatMessageData:(UIButton *)btn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    CrazyChatMineGoodsCell *cell = (CrazyChatMineGoodsCell *)btn.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    [self repeatMessageDataWithIndex:indexPath.row];
}
//订单
- (void)clickOrderRepeatMessageData:(UIButton *)btn {
    //关闭播放的语音
    if (isClickPlayVoice) {
        [self closeNowPlayVoice];
    }
    CrazyChatMineOrderCell *cell = (CrazyChatMineOrderCell *)btn.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    [self repeatMessageDataWithIndex:indexPath.row];
}
//重发
- (void)repeatMessageDataWithIndex:(NSInteger)index {
    CrazyChatDataModel *model = self.CrazyChatDataArray[index];
    //发送数据
    [self CrazyChatSendMessageWithMessageID:model.MESSAGE_ID messageData:model.MESSAGE_DATA messageType:model.MESSAGE_TYPE];
}

#pragma mark 给webSocket发送消息
- (void)CrazyChatSendMessageWithMessageID:(NSString *)message_id messageData:(NSString *)messageData messageType:(NSString *)messageType {
    NSDictionary *params = @{@"TYPE" : @"MESSAGE",
                             @"DATA" : @{@"MESSAGE_ID" : message_id,
                                         @"MESSAGE_TYPE" : messageType,
                                         @"MESSAGE_DATA" : messageData,
                                         @"TARGET_TYPE" : @"CUSTOMER",
                                         @"TARGET_ID" : self.store_id,
                                         @"DIVERSION_ID" : self.diversionID
                                         }
                             };
    //发送数据
    [[CrazySocketUtility sharedSocketManager] sendDataToServer:params];
}

#pragma mark 发送语音
- (void)CrazyChatSendVoiceData:(NSNotification *)sender {
    NSDictionary *userInfo = sender.userInfo;
    NSString *urlString = userInfo[@"voiceURL"];
    NSString *timeString = [Crazy_TimeChange currentTimeChangeTimeString];
    NSString *voiceTime = userInfo[@"voiceTime"];
    NSDictionary *params = @{@"TYPE" : @"MESSAGE",
                             @"DATA" : @{@"MESSAGE_ID" : timeString,
                                         @"MESSAGE_TYPE" : @"VOICE",
                                         @"MESSAGE_DATA" : urlString,
                                         @"VOICE_TIME" : voiceTime,
                                         @"TARGET_TYPE" : @"CUSTOMER",
                                         @"TARGET_ID" : self.store_id,
                                         @"DIVERSION_ID" : self.diversionID
                                         }
                             };
    
    CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
    model.MESSAGE_DATA = urlString;
    model.FORM_TYPE = @"USER";
    model.MESSAGE_ID = timeString;
    model.MESSAGE_TYPE = @"VOICE";
    model.VOICE_TIME = voiceTime;
    model.repeatType = @"1";
    [self.CrazyChatDataArray addObject:model];
    [_chatTableView reloadData];
    //发送数据
    [[CrazySocketUtility sharedSocketManager] sendDataToServer:params];
}

#pragma mark 播放语音
- (void)clickPlayVoiceBtn:(UIButton *)sender {
    CrazyChatMineVoiceCell *cell = (CrazyChatMineVoiceCell *)sender.superview.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    if (selectIndexPath == indexPath) {
        //关闭播放的语音
        [self closeNowPlayVoice];
    } else {
        //关闭播放的语音
        [self closeNowPlayVoice];
        //播放的地址
        CrazyChatDataModel *dataModel = self.CrazyChatDataArray[indexPath.row];
        dataModel.isPlayVoice = YES;
        _player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:dataModel.MESSAGE_DATA]];
        _player.automaticallyWaitsToMinimizeStalling = NO;
        [_player play];
        isClickPlayVoice = YES;
        selectIndexPath = indexPath;
        [_chatTableView reloadData];
    }
}
//把播放的按钮关闭
- (void)closeNowPlayVoice {
    if (selectIndexPath.row != -1) {
        CrazyChatDataModel *dataModel = self.CrazyChatDataArray[selectIndexPath.row];
        dataModel.isPlayVoice = NO;
    }
    [_player pause];
    isClickPlayVoice = NO;
    selectIndexPath = [NSIndexPath indexPathForRow:-1 inSection:-1];
    [_chatTableView reloadData];
}

#pragma mark 刷新
- (void)createRefresh {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, 20)];
    self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityView.frame = CGRectMake(headerView.width / 2, 0, 20, 20);
    [headerView addSubview:self.activityView];
    _chatTableView.tableHeaderView = headerView;
    headerView.hidden = YES;
}
#pragma mark 获取店铺信息
- (void)getStoreMessageData {
    NSString *urlString = [CRAZY_CHAT_API_DOMIN stringByAppendingString:@"customer/getStoreInfo"];
    NSDictionary *params = @{@"store_id" : self.store_id};
    CrazyWeakSelf;
    [CrazyNetWork CrazyRequest_Post:urlString HUD:NO parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@",dic[@"code"]] isEqualToString:@"0"]) {
            NSDictionary *dataDict = dic[@"data"];
            //店铺名称
            weakSelf.shopName = [NSString stringWithFormat:@"%@", dataDict[@"store_name"]];
            //店铺logo
            weakSelf.shopHeadURL = [NSString stringWithFormat:@"%@", dataDict[@"logo"]];
            //标题
            weakSelf.CrazyChatTitleLabel.text = weakSelf.shopName;
        }
    } fail:^(NSError *error, NSString *url) {
        
    }];
}

#pragma mark 获取历史消息
- (void)getHistoryMessageData {
    NSString *urlString = [NSString stringWithFormat:@"%@%@", CRAZY_CHAT_API_DOMIN, @"customer/getChatLog"];
    NSDictionary *params = @{@"limit" : CRAZY_CHAT_MAX_COUNT, @"store_id" : self.store_id, @"last_id" : lastDataID, @"member_id" : UID, @"first_message_time" : lastDataID};
    CrazyWeakSelf;
    [CrazyNetWork CrazyRequest_Post:urlString HUD:YES parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@",dic[@"code"]] isEqualToString:@"0"]) {
            [weakSelf receiveDataWith:dic];
        } else {
            [JKToast showWithText:dic[@"data"]];
        }
    } fail:^(NSError *error, NSString *url) {
    }];
}
//保存数据
- (void)receiveDataWith:(NSDictionary *)dic {
    NSMutableArray *historyArray = [NSMutableArray array];
    if ([dic[@"data"] count] == 0) {
        self.isRefresh = YES;
    }
    for (NSDictionary *dict in dic[@"data"]) {
        CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
        [model setHistoryValues:dict tableView:_chatTableView];
        [historyArray addObject:model];
    }
    [self.CrazyChatDataArray insertObjects:historyArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, historyArray.count)]];
    [_chatTableView reloadData];
    if ([lastDataID isEqualToString:@"0"]) {
        [self removeTableViewToLastData];
    }
    //保存最后一条的ID
    CrazyChatDataModel *model = [self.CrazyChatDataArray firstObject];
    lastDataID = model.MESSAGE_ID;
}
#pragma mark 滑动获取更多历史记录
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0  && _isRefresh == NO) {
        self.isRefresh = YES;
        [self getHistoryMessageMoreData];
    }
}
//更多历史记录
- (void)getHistoryMessageMoreData {
    NSString *urlString = [NSString stringWithFormat:@"%@%@", CRAZY_CHAT_API_DOMIN, @"customer/getChatLog"];
    NSDictionary *params = @{@"limit" : CRAZY_CHAT_MAX_COUNT, @"store_id" : self.store_id, @"last_id" : lastDataID, @"member_id" : UID, @"first_message_time" : lastDataID};
    CrazyWeakSelf;
    [CrazyNetWork CrazyRequest_Post:urlString HUD:NO parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@",dic[@"code"]] isEqualToString:@"0"]) {
            [weakSelf receiveMoreDataWith:dic];
        } else {
            [JKToast showWithText:dic[@"data"]];
        }
    } fail:^(NSError *error, NSString *url) {
        weakSelf.isRefresh = NO;
        _chatTableView.tableHeaderView.hidden = YES;
        [weakSelf.activityView stopAnimating];
    }];
}
//保存数据
- (void)receiveMoreDataWith:(NSDictionary *)dic {
    if ([dic[@"data"] count] > 0) {
        _chatTableView.tableHeaderView.hidden = NO;
        [self.activityView startAnimating];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSMutableArray *historyArray = [NSMutableArray array];
            for (NSDictionary *dict in dic[@"data"]) {
                CrazyChatDataModel *model = [[CrazyChatDataModel alloc] init];
                [model setHistoryValues:dict tableView:_chatTableView];
                [historyArray addObject:model];
            }
            [self.CrazyChatDataArray insertObjects:historyArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, historyArray.count)]];
            [_chatTableView reloadData];
            self.isRefresh = NO;
            _chatTableView.tableHeaderView.hidden = YES;
            [self.activityView stopAnimating];
            //保存最后一条的ID
            CrazyChatDataModel *model = [self.CrazyChatDataArray firstObject];
            lastDataID = model.MESSAGE_ID;
        });
    }
}

#pragma mark 查看宝贝
//客服发送的
- (void)clickCheckCustomSendGoodsBtn:(UIButton *)btn {
    CrazyChatCustomGoodsCell *cell = (CrazyChatCustomGoodsCell *)btn.superview.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    [self clickCheckGoodsLinkMessageWith:model.MESSAGE_DATA];
}
//自己发送的
- (void)clickCheckMineSendGoodsBtn:(UIButton *)btn {
    CrazyChatMineGoodsCell *cell = (CrazyChatMineGoodsCell *)btn.superview.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    [self clickCheckGoodsLinkMessageWith:model.MESSAGE_DATA];
}
- (void)clickCheckGoodsLinkMessageWith:(NSString *)goodsID {
}

#pragma mark 查看订单
//客服发送的
- (void)clickCheckCustomSendOrderBtn:(UIButton *)btn {
    CrazyChatCustomOrderCell *cell = (CrazyChatCustomOrderCell *)btn.superview.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    [self clickCheckOrderMessageWithGoodsID:model.GOODS_ID orderID:model.MESSAGE_DATA];
}
//自己发送的
- (void)clickCheckMineSendOrderBtn:(UIButton *)btn {
    CrazyChatMineOrderCell *cell = (CrazyChatMineOrderCell *)btn.superview.superview.superview;
    NSIndexPath *indexPath = [_chatTableView indexPathForCell:cell];
    CrazyChatDataModel *model = self.CrazyChatDataArray[indexPath.row];
    [self clickCheckOrderMessageWithGoodsID:model.GOODS_ID orderID:model.MESSAGE_DATA];
}
- (void)clickCheckOrderMessageWithGoodsID:(NSString *)goodsID orderID:(NSString *)orderID {
}

#pragma mark 文本类消息处理
- (NSMutableAttributedString *)textChangeWithText:(NSString *)text {
    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *reultArray = [regularExpression matchesInString:attriString.string options:NSMatchingReportCompletion range:NSMakeRange(0, attriString.string.length)];
    
    for (NSInteger i = reultArray.count - 1; i >= 0; i--) {
        NSTextCheckingResult *result = reultArray[i];
        NSString *rangeStr = [attriString.string substringWithRange:result.range];
        UIImage *image = [self getImageWithRangeString:rangeStr];
        if (image != nil) {
            NSTextAttachment *imageTextAtt = [[NSTextAttachment alloc] init];
            imageTextAtt.image = image;
            imageTextAtt.bounds = CGRectMake(0, -6, 22, 22);
            NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageTextAtt];
            
            [attriString replaceCharactersInRange:result.range withAttributedString:imageAtt];
        }
    }
    
    return attriString;
}
//更换成表情
- (UIImage *)getImageWithRangeString:(NSString *)rangeStr  {
    for (CrazyChatExpressionModel *model in self.expressionArray) {
        if ([model.name isEqualToString:rangeStr]) {
            NSString *imageStr = model.image;
            UIImage *image = [UIImage imageNamed:imageStr];
            return image;
        }
    }
    return nil;
}

#pragma mark 懒加载
//数据源
- (NSMutableArray *)CrazyChatDataArray {
    if (_CrazyChatDataArray == nil) {
        _CrazyChatDataArray = [NSMutableArray array];
    }
    return _CrazyChatDataArray;
}
//表情数组
- (NSMutableArray *)expressionArray {
    if (_expressionArray == nil) {
        _expressionArray = [NSMutableArray array];
    }
    return _expressionArray;
}
//设置
- (UIButton *)CrazyChatSettingBtn {
    if (_CrazyChatSettingBtn == nil) {
        _CrazyChatSettingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _CrazyChatSettingBtn.size = CGSizeMake(30, 30);
        [_CrazyChatSettingBtn setImage:[UIImage imageNamed:@"CrazyChat_setting@2x.png"] forState:UIControlStateNormal];
        [_CrazyChatSettingBtn addTarget:self action:@selector(clickNavigationRightSettingItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _CrazyChatSettingBtn;
}
//进店
- (UIButton *)CrazyChatGoShopBtn {
    if (_CrazyChatGoShopBtn == nil) {
        _CrazyChatGoShopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _CrazyChatGoShopBtn.size = CGSizeMake(40, 20);
        _CrazyChatGoShopBtn.backgroundColor = CRAZY_BACK_COLOR;
        [_CrazyChatGoShopBtn setTitle:@"进店" forState:UIControlStateNormal];
        _CrazyChatGoShopBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_CrazyChatGoShopBtn corner_radius:5];
        [_CrazyChatGoShopBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_CrazyChatGoShopBtn addTarget:self action:@selector(clickNavigationRightGoItem) forControlEvents:UIControlEventTouchUpInside];
    }
    return _CrazyChatGoShopBtn;
}
//标题
- (UILabel *)CrazyChatTitleLabel {
    if (_CrazyChatTitleLabel == nil) {
        _CrazyChatTitleLabel = [[UILabel alloc] init];
        _CrazyChatTitleLabel.size = CGSizeMake(CRAZY_SCREEN_WIDTH / 2, 30);
        _CrazyChatTitleLabel.textColor = CRAZY_RGBR(0);
        _CrazyChatTitleLabel.textAlignment = NSTextAlignmentCenter;
        _CrazyChatTitleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _CrazyChatTitleLabel;
}

- (void)setHideHeight:(CGFloat)hideHeight {
    _hideHeight = hideHeight;
    self.inputBackView.y = CRAZY_SCREEN_HEIGHT - hideHeight - CRAZY_HOME_HEIGHT - 50;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
